package com.yyi.springcloud.controller;


import com.yyi.springcloud.common.ResponseResult;
import com.yyi.springcloud.common.SearchResult;
import com.yyi.springcloud.entities.SearchInfoModel;
import com.yyi.springcloud.service.Local_SearchInfoService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.util.List;

@Controller
@RequestMapping("/mysqlapi/SearchInfoAPI")
public class Mysql_SearchInfoController {
	@Resource
	private Local_SearchInfoService searchInfoservice;

	/**
	 * 根据关键字查询信息
	 * @param keyword
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/getInfo", method = RequestMethod.GET)
	public List<SearchInfoModel> getInfo(String keyword) {
		try {
			keyword = new String(keyword.getBytes("iso-8859-1"), "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return searchInfoservice.getSearchInfo(keyword);
	}

	//2.按铭牌信息所有字段模糊查询
    //http://localhost:8080/bxxs/api/SearchInfoAPI/getSearchData.do
	@RequestMapping(value = "/getSearchData", method = RequestMethod.GET)
	@ResponseBody
	public ResponseResult getIspByName(String queryString) {
		SearchResult searchResult = null;
		try {
			queryString = new String(queryString.getBytes("iso8859-1"), "utf-8");
			searchResult = searchInfoservice.searchService(queryString, 1, 10);
		} catch (Exception e) {
			e.printStackTrace();
			return ResponseResult.build(500, getStackTrace(e));
		}
		return ResponseResult.ok(searchResult);
	}

	/**
	 * 3.导入数据到索引库
	 */
	//http://localhost:8080/bxxs/api/SearchInfoAPI/importAllSearchData.do
	@RequestMapping("/importAllSearchData")
	@ResponseBody
	public String importAllSearchData() {
		return searchInfoservice.importAllSearchData();
	}


	/**
	 * 获取异常的堆栈信息
	 */
	public static String getStackTrace(Throwable t) {
		StringWriter sw = new StringWriter();
		PrintWriter pw = new PrintWriter(sw);
		try {
			t.printStackTrace(pw);
			return sw.toString();
		} finally {
			pw.close();
		}
	}

}
